/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.common.util.encrypt.Des3
 * <p>
 * 类产生时间: 2014-12-19 23:37
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 项目组 : 苏州公安移动门户
 * <p>
 * 部门: 手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.common.util.encrypt;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * DES3工具类
 *
 * @author chenw
 * @time 2014-12-19 23:37
 */
public class Des3 {
    private String key;
    private byte[] ivBytes;

    private Des3() {
    }

    public Des3(String key) {
        if (key.length() > 8) {
            key = key.substring(0, 8);
        }
        this.key = key;
        this.ivBytes = key.getBytes();
    }

    public String encodeStr(String message) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        byte[] keys = this.key.getBytes();
        DESKeySpec desKeySpec = new DESKeySpec(keys);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(this.ivBytes);
        cipher.init(1, secretKey, iv);
        byte[] data = cipher.doFinal(message.getBytes("UTF-8"));
        return Base64.encode(data);
    }

    public String decodeStr(String message) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        byte[] keys = this.key.getBytes();
        DESKeySpec desKeySpec = new DESKeySpec(keys);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(this.ivBytes);
        cipher.init(2, secretKey, iv);
        byte[] data = cipher.doFinal(Base64.decode(message.getBytes("utf-8")));
        return new String(data, "UTF-8");
    }
}
